﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace DLR05
{
	public static class TypeHelper
	{
		public static Type FindType(string typeName)
		{
			// Give the executing assembly search priority:
			var type = Assembly.GetExecutingAssembly().GetTypes()
				.Where(t => (t.Name == typeName) || (t.FullName == typeName))
				.FirstOrDefault();

			if (type == null)
			{
				type = AppDomain.CurrentDomain.GetAssemblies()
					.Where(asm => !asm.FullName.StartsWith("Microsoft.") && !asm.FullName.StartsWith("System."))
					.Select(asm => asm.GetTypes())
					.Aggregate(new List<Type>(), (list, types) => { list.AddRange(types); return list; })
					.Where(t => (t.Name == typeName) || (t.FullName == typeName))
					.FirstOrDefault();
			}
			return type;
		}
	}
}